importScripts('./db.js');
importScripts('./network.js');

const CACHE_NAME = 'cache-demo';

self.addEventListener('fetch', function(event) {
  console.log('fetch');
  // event.respondWith(
  //   caches.match(event.request).then(function(response) {
  //     if (response) {
  //       return response;
  //     }
  //     const fetchRequest = event.request.clone();
  //     return fetch(fetchRequest).then(function(response) {
  //       const responseToCache = response.clone();
  //       caches.open(CACHE_NAME).then(function(cache) {
  //         cache.put(event.request, responseToCache);
  //       });
  //       return response;
  //     });
  //   })
  // );
});

self.addEventListener('sync', function(event) {
  console.log('sync');

  // ======================== sync
  if (event.tag === 'add-todo') {
    const date = new Date();
    console.log(`开始运行后台同步: ${event.tag}`);
    console.log(`第 ${retryTimes++} 次同步: ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`);
    if (event.lastChance) {
      console.log('这是最后一次尝试!!');
    }
    event.waitUntil(
      db.getTodos().then(function(todos) {
        return network.addTodos(todos).then(function(todos) {
          console.log('来自服务器的响应:', todos);
          notification(todos);
          return db.clearTodos();
        });
      })
    );
  }
  // ======================== sync


});

self.addEventListener('message', function(event) {
  console.log('message');
});

self.addEventListener('push', function(event) {
  console.log('push');
  const data = event.data.json();
  const title = 'Push & Notification Demo';
  console.log('触发通知响应事件:', data);
  if (data.type === 'subscribe') {
    event.waitUntil(
      self.registration.showNotification(title, {
        body: data.message,
        icon: './images/launcher-icon.png',
      })
    );
  } else if (data.type === 'vote') {
    event.waitUntil(
      self.registration.showNotification(title, {
        body: data.message,
        icon: './images/launcher-icon.png',
        actions: [
          { action: 'like', title: '👍 喜欢' },
          { action: 'unlike', title: '👎 不喜欢' }
        ]
      })
    );
  }
});

self.addEventListener('notificationclick', function(event) {
  console.log('notificationclick');
  event.notification.close();
  console.log('触发通知事件:');
  if (event.action === 'like') {
    console.log(`你对 ${event.notification.body} 透了赞成票`);
  } else if (event.action === 'unlike') {
    console.log(`你对 ${event.notification.body} 投了反对票`);
  }
});

self.addEventListener('install', function(event) {

  console.log('install');

  // self.skipWaiting();

  event.waitUntil(
    caches.open(CACHE_NAME).then(function(cache) {
      return cache.addAll([
        './',
        './index.html',
        './style.css',
        './main.js',
        './images/launcher-icon.png'
      ]);
    })
  );

});

/**
 * 对缓存进行更新或删除
 */
self.addEventListener('activate', function(event) {

  // self.clients.claim();

  console.log('activated!!!');

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheName) {
          console.log(`cacheName - ${cacheName}`);
          return cacheName != CACHE_NAME;
        }).map(function(cacheName) {
          return caches.delete(cacheName);
        })
      );
    })
  );


});

function notification(todos) {
  console.log('notification!!!');
  console.log(todos);
  self.clients.matchAll().then(function(clients) {
    if (clients && clients.length) {
      clients.forEach(function(client) {
        console.log('before post message!!!');
        console.log(todos);
        client.postMessage(todos);
      });
    }
  });
}

let retryTimes = 1;
